import { SerialPort } from "serialport"
let gWinMain = null

const port = new SerialPort({
  path: "COM1",
  baudRate: 9600,
  autoOpen: false
})

port.on("error", (err) => {
  console.error("error：" + err.message + "\n")
})

const STX = 0x02
const ETX = 0x03

let cache = Buffer.alloc(0) // 缓存区
port.on("data", (data) => {
  cache = Buffer.concat([cache, data])
  while (true) {
    const start = cache.indexOf(STX)
    const end = cache.indexOf(ETX)

    if (start === -1 || end === -1 || end < start) {
      // 数据不完整，等下次再拼接
      break
    }
    // 提取一帧（包含STX和ETX）
    const frame = cache.slice(start, end + 1)
    // 解析这帧
    parseFrame(frame)
    // 移除已解析部分，继续查找后面是否还有完整帧
    cache = cache.slice(end + 1)
  }
})

function parseFrame(frame) {
  // 去掉STX和ETX
  const asciiPart = frame.slice(1, frame.length - 1).toString("ascii")

  const sign = asciiPart[0] // + 或 -
  const numberStr = asciiPart.slice(1, -3) // 数字部分
  const status = asciiPart.slice(-3) // 状态/单位码

  let weight = parseInt(numberStr, 10)
  if (sign === "-") {
    weight = -weight
  }
  const weightInfo = {
    raw: asciiPart,
    sign,
    weight,
    status
  }
  console.log("weight: " + weight)
  gWinMain?.webContents?.send("weightInfo", weightInfo)
}

export function openPort(winMain) {
  gWinMain = winMain
  port.open((err) => {
    if (err) {
      console.error("port open fail" + err.message + "\n")
      return
    }
    console.log("port open ok\n")
    // setInterval(() => {
    //   gWinMain?.webContents?.send("weightInfo", { weight: Date.now() })
    //   console.error("send weightInfo")
    // }, 3000)
  })
}
